package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 全局异常处理
 */
@Slf4j
@ResponseBody
@ControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionHandler {

    /**
     * 异常处理方法
     *
     * @return
     */
    @ExceptionHandler(DuplicateKeyException.class)
    public R<String> exceptionHandler(DuplicateKeyException ex) {
        log.error("bug: Duplicate entry", ex);

        String[] split = ex.getMessage().split(" ");
        String msg = (split[9] + "已存在").replace("'", "");

        return R.error(msg);
    }

    /**
     * 异常处理方法
     *
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex) {
        log.error("bug: Custom error", ex);
        return R.error(ex.getMessage());
    }

    /**
     * 兜底的异常
     *
     * @return
     */
    @ExceptionHandler(Exception.class)
    public R<String> exceptionHandler(Exception ex) {
        log.error("bug: unknown error", ex);
        return R.error("您的网络异常,请稍后重试!");
    }

}
